import _ from 'lodash'

export default class Node {
    constructor(type = null, meta = null, data = null) {
        this.type = type
        this.meta = meta
        this.data = data
        this.parent = null
        this.children = []
    }
    addChild(node) {
        this.children.push(node)
        node.parent = this
    }
    removeChild(node) {
        this.children = _.remove(this.children, child => child.meta.id !== node.meta.id)
    }
    setWidth(width) {
        this.meta.width = width
    }
    // 计算当前节点相对于最左侧的宽度
    getAllWidth() {
        let allWidth = this.meta.width
        let parent = this.parent
        let count = 0
        while (parent) {
            count++
            allWidth += parent.meta.width
            parent = parent.parent
        }
        return allWidth + count * 40
    }
    // 计算当前节点高度
    getAllHeight() {
        if (this.children.length === 0 || this.children.length === 1) {
            return 50 // 节点高度，固定值
        }
        let nodes = this.nodes()
        let minY = 0, maxY = 0
        nodes.forEach(node => {
            if (node.meta.y > maxY) {
                maxY = node.meta.y
            }
            if (node.data.y < minY) {
                minY = node.meta.y
            }
        })
        return maxY - minY + 50
    }
    setData(data) {
        if (!data) {
            throw new Error('data is undefined')
        }
        this.data = data
    }
    setId(id) {
        this.meta.id = id
    }
    nodes() {
        let nodes = [], queue = []
        queue.push(this)
        let currentNode = queue.shift()
        while(currentNode) {
            nodes.push(currentNode)
            queue.push(...currentNode.children)
            currentNode = queue.shift()
        }
        return nodes
    }
    maxId() {
        let nodes = this.nodes()
        let maxId = 0
        nodes.forEach(node => {
            if (node.meta.id > maxId) {
                maxId = node.meta.id
            }
        })
        return maxId
    }
}